<template>
  <div class="white-module">
    <div class="scholl-tabs">
      <el-button
        v-if="userType == 3"
        class="tabs-btn"
        type="primary"
        @click="showClassRoomDialog"
        >添加课堂</el-button
      >
      <el-tabs v-model="activeName">
        <el-tab-pane label="课堂列表" name="first"></el-tab-pane>
      </el-tabs>
    </div>
    <el-row class="search-module">
      <el-form
        :inline="true"
        :model="dataForm"
        @keyup.enter="getDataList()"
        style="width: 100%"
      >
        <el-col class="search-left" :span="18">
          课程名称：<el-input
            v-model="dataForm.title"
            placeholder="请输入课程名称"
          />
          <span class="interval"></span>
        </el-col>
        <el-col class="right-btn" :span="6">
          <el-button type="primary" @click="getDataList()">查询</el-button>
          <el-button type="default">重置</el-button>
        </el-col>
      </el-form>
    </el-row>
    <div class="global-table">
      <el-table
        :data="dataList"
        :header-cell-style="{
          background: '#F5F7FA',
          color: '#333',
        }"
        style="width: 100%"
      >
        <el-table-column prop="title" label="课堂名称" />
        <el-table-column prop="teacher" label="授课老师" />
        <el-table-column prop="status" label="状态">
          <template v-slot="scope">
            <el-tag v-if="scope.row.status === 0" size="small">未开始</el-tag>
            <el-tag v-else-if="scope.row.status === 1" size="small"
              >上课中</el-tag
            >
            <el-tag v-else size="small" type="danger">已结束</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320">
          <template #default="scope">
            <el-button
              type="text"
              size="small"
              @click="startClass(scope.row.id)"
            >
              开始上课
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="assistClass(scope.row.id)"
            >
              辅助资料
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="evaluation(scope.row.id)"
              v-if="userType == 3 || (userType == 4) && scope.row.answerNum == 0 &&scope.row.questionStatus !=0 "
            >
              课堂评价
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="updClassRoom(scope.row.id)"
              v-if="userType == 3 "
            >
              编辑
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="remove(scope.row.id)"
              v-if="userType == 3"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-row class="global-pagination">
      <el-col :span="8" class="total"> 共搜索 {{ total }} 条数据 </el-col>
      <el-col :span="16">
        <el-pagination
          background
          layout="  prev, pager, next, jumper"
          :current-page="page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="limit"
          :total="total"
          :small="false"
          :disabled="false"
          @size-change="query"
          @current-change="pageCurrentChangeHandle"
        />
      </el-col>
    </el-row>

    <!--辅助资料-->
    <el-dialog title="辅助资料" v-model="assistDialogShow" width="700px">
      <div style="text-align: center" class="student">
        <div
          style="
            border: #f7f7f7 solid 1px;
            margin-bottom: 5px;
            border-radius: 5px;
            height: 300px;
          "
        >
          <el-tree
            :data="list"
            show-checkbox
            node-key="id"
            ref="tree"
            :default-expanded-keys="[-977223679, -893337598]"
            :default-checked-keys="defaultSelectedTree"
            :props="defaultProps"
            @check="currentChecked"
          />
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="assistDialogShow = false">取 消</el-button>
          <el-button type="primary" @click="queding">确 定</el-button>
        </span>
      </div>
    </el-dialog>

    <!--学生管理-->
    <el-dialog title="添加学生" v-model="studentDialogShow" width="700px">
      <div style="text-align: center" class="student">
        <el-transfer
          filterable
          :titles="['全部学生', '选中学生']"
          :button-texts="['', '']"
          v-model="classhourStudent"
          :data="studentList"
        >
        </el-transfer>

        <span slot="footer" class="dialog-footer">
          <el-button @click="studentDialogShow = false">取 消</el-button>
          <el-button type="primary" @click="studentDialogShow = false"
            >确 定</el-button
          >
        </span>
      </div>
    </el-dialog>

    <!--添加课堂-->
    <el-dialog title="添加课堂" v-model="classRoomDialogShow" width="700px">
      <div style="text-align: center" class="student">
        <el-form
          :model="dataForm"
          :rules="dataRule"
          ref="dataFormRef"
          label-width="120px"
        >
          <el-form-item label="课堂名称">
            <el-input v-model="editForm.title" placeholder="请输入课堂名称" />
          </el-form-item>
          <!--课程列表-->
          <el-form-item label="选择课程">
            <el-select
              class="m-2"
              v-model="editForm.courseId"
              placeholder="请选择课程"
              @change="queryClassHourList(editForm.courseId)"
            >
              <el-option
                v-for="item in courseSelectedList"
                :label="item.title"
                :value="item.id"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-transfer
            filterable
            :titles="['全部课时', '选中课时']"
            :button-texts="['', '']"
            v-model="editForm.classHourIds"
            :data="classHourList"
          >
          </el-transfer>

          <span slot="footer" class="dialog-footer">
            <el-button @click="classRoomDialogShow = false">取 消</el-button>
            <el-button type="primary" @click="saveClassHour">确 定</el-button>
          </span>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, ref } from "vue";
import listService from "@/service/listService";
import router from "@/router";
import baseService from "@/service/baseService";
import { ElMessage, ElMessageBox, ElTable } from "element-plus";
import { getCache } from "@/utils/cache";

export default defineComponent({
  setup() {
    const state = reactive({
      getDataListURL: "/fii/front/classRoom/page",
      getDataListIsPage: true,
      deleteURL: "/pay/order",
      deleteIsBatch: true,
      dataForm: {
        title: "",
        status: "",
        userId: "",
      },
      editForm: {
        id: 0,
        title: "",
        courseId: "",
        classHourIds: [-1,-2],
      },
    });
    return { ...listService(state), ...toRefs(state) };
  },

  data() {
    return {
      defaultProps: {
        children: "children",
        label: "label",
      },
      list: [
        {
          id: 1,
          label: "Level one 1",
          pid: 0,
          children: [
            {
              id: 4,
              label: "Level two 1-1",
              pid: 1,
              children: [
                {
                  id: 9,
                  label: "Level three 1-1-1",
                  pid: 4,
                },
                {
                  id: 10,
                  label: "Level three 1-1-2",
                  pid: 4,
                },
              ],
            },
          ],
        },
      ],
      //辅助学习
      assistDialogShow: false,
      //设置老师
      teacherDialogShow: false,
      //管理学生
      studentDialogShow: false,
      //添加课堂
      classRoomDialogShow: false,
      //学生列表
      studentList: [
        {
          key: 1,
          label: "北京",
          disabled: false,
        },
        {
          key: 2,
          label: "上海",
          disabled: false,
        },
        {
          key: 3,
          label: "广州",
          disabled: false,
        },
      ],
      classhourStudent: [],
      courseSelectedList: [],
      updateForm: {
        id: null,
        schoolName: "",
      },
      classHourList: [{ key: "", label: "", disabled: false }],
      userType: null,
      assistClassId: 0,
      SelectedObjs: "",
      defaultSelectedTree: []
    };
  },

  mounted() {
    //取当前用户的登录类型
    this.userType = getCache("userType", { isSessionStorage: true }, {});
  },

  methods: {
    //获取树形图选中的id
    currentChecked(nodeObj: any, SelectedObj: any) {
      this.SelectedObjs = SelectedObj.checkedKeys;
    },

    /**
     * 查询树形菜单
     */
    querySpaceTreeList() {
      this.defaultSelectedTree = [];
      baseService.post("/fii/front/space/fileTree", {classRoomId: this.assistClassId}).then((res) => {
        if (res.code === 0) {
          this.list = res.data.spaceTreeList;
          this.defaultSelectedTree = res.data.spaceTreeSelectedList;
        }
      });
    },

    /*
     *辅助学习
     */
    assistClass(id: number) {
      this.assistDialogShow = true;
      this.assistClassId = id;
      // 获取辅助资料树形结构接口
      this.querySpaceTreeList();
    },

    queding() {
      this.assistDialogShow = false;
      baseService
        .post("/fii/front/classRoom/saveFiles", {
          classRoomId: this.assistClassId,
          fileIds: this.SelectedObjs,
        })
        .then((res) => {
          if (res.code === 0) {
            this.courseSelectedList = res.data.list;
          }
        });
    },
    /**
     * 开始上课
     */
    startClass(id: number) {
      baseService
        .post("/fii/front/classRoom/startClass", { classRoomId: id })
        .then((res) => {
          if (res.code === 0) {
            router.push({
              path: "/classroom/study",
              query: { id: id, type: 3 },
            });
          } else {
            ElMessage.error(res.msg);
          }
        });
    },

    /**
     * 课堂评价
     */
    evaluation(id: number) {
      router.push({ path: "/classroom/study", query: { id: id, type: 1 } });
    },
    /**
     * 课堂评价
     */
    evaluationEdit(id: number) {
      router.push({path: "/classroom/study", query: {id: id, type: 1}});
    },

    /**
     * 编辑课堂
     */
    updClassRoom(id: number) {
      console.log("------------");
      this.editForm.id = id
      this.queryClassRoomById(id);
      this.classRoomDialogShow = true;
    },

    /**
     * 添加课堂
     */
    showClassRoomDialog() {
      console.log("------------");
      this.classRoomDialogShow = true;
      this.querySelectedSchool();
    },

    /**
     * 保存课堂
     */
    saveClassHour(id: number) {
      baseService
        .post("/fii/front/classRoom/addOrUpdate", this.editForm)
        .then((res) => {
          if (res.code === 0) {
            this.classRoomDialogShow = false;
            this.query();
          }
        });
    },

    /**
     * 查询课程 - 已选择课程
     */
    querySelectedSchool() {
      const userInfo = getCache("CacheToken", { isSessionStorage: true }, {});

      baseService
        .get("/fii/front/fiicourse/querySelectedShoolCourse", {
          schoolId: userInfo.schoolId,
          page: 1,
          limit: 1000,
        })
        .then((res) => {
          if (res.code === 0) {
            this.courseSelectedList = res.data.list;
          }
        });
    },

    //获取课程的所有课时列表
    queryClassHourList(courseId: string) {
      this.classHourList = [];
      baseService
        .post("/fii/front/classRoom/queryClassHourList", {
          courseId: courseId + "",
        })
        .then((res) => {
          if (res.code === 0) {
            let list = res.data.classHourList;
            for (let i = 0; i < list.length; i++) {
              const item = { key: "", label: "", disabled: false };
              const one = list[i];
              item.key = one.id;
              item.label = one.title;
              item.disabled = false;
              this.classHourList.push(item);
            }
            console.log(this.classHourList);
          }
        });
    },

    // 获取课堂信息
    queryClassRoomById(classRoomId: number) {
      this.querySelectedSchool();
      baseService
          .post("/fii/front/classRoom/queryClassRoom", {
            classRoomId: classRoomId + "",
          })
          .then((res) => {
            if (res.code === 0) {
              console.log(res.data);
              let classRoomEntity = res.data.classRoomEntity
              this.editForm.title = classRoomEntity.title
              this.editForm.courseId = classRoomEntity.courseId
              //this.editForm.classHourIds = classRoomEntity.classHourId.split(',')
              let classHourArr = classRoomEntity.classHourId.split(',')
              const classHourIds = []
              for(let item of classHourArr){
                classHourIds.push(item*1)
              }
              this.editForm.classHourIds = classHourIds
              console.log(this.editForm.classHourIds)
              this.queryClassHourList(this.editForm.courseId)
            }
          });
    },

    /**
     * 删除课堂
     * @param id
     */
    remove(id: number) {
      ElMessageBox.confirm("确定删除课堂, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          baseService
            .post("/fii/front/classRoom/delete", { id: id })
            .then((res) => {
              if (res.code === 0) {
                this.classRoomDialogShow = false;
                this.query();
              }
            });
        })
        .catch(() => {});
    },



    payHandle(orderId: string) {
      //window.open(`${app.api}/pay/alipay/webPay?orderId=` + orderId);
    },
  },
});
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss">
.search-module {
  display: flex;
  justify-content: space-between;
  padding: 0px 20px 0px 20px;
  margin-top: 10px;
  .interval {
    padding: 0px 15px;
  }

  .search-left {
    color: #333333;
    text-align: left;
  }
  .right-btn {
    text-align: right;
  }
}
.global-table {
  margin-top: 15px;
  padding: 0px 20px;
}

.popper-menu {
  border: 0px !important;
  .el-menu {
    padding: 0px !important;
    background-color: #008fd1 !important;
    .el-menu-item-group__title {
      padding: 0px;
    }
    .el-menu-item:hover {
      background-color: #ffffff !important;
      color: #00a0e9;
    }

    .el-menu-item.is-active {
      background-color: #ffffff !important;
    }
  }
}

.dialog-footer {
  margin-top: 10px;
}
</style>
